#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>

int main(int argc,char* argv[])
{
	if(argc != 3)
	{
		std::cout<<"参数不足!"<<std::endl;
		return 1;
	}
	int sock = socket(AF_INET,SOCK_DGRAM,0);
	
	char buffer[1024];
	
	struct sockaddr_in dest;
	dest.sin_family = AF_INET;
	dest.sin_port = htons(atoi(argv[2]));
	dest.sin_addr.s_addr = inet_addr(argv[1]);

	while(1)
	{
		std::cout<<"[晓林@centos]# ";
		fflush(stdout);
		buffer[0] = 0;
		ssize_t size = read(0,buffer,sizeof(buffer)-1);
		if(size > 0)
		{
			buffer[size-1] = 0;
			sendto(sock,buffer,strlen(buffer),0,(struct sockaddr*)&dest,sizeof(dest));

			struct sockaddr_in other;
			socklen_t len = sizeof(other);
			ssize_t s = recvfrom(sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&other,&len);
			if(s > 0)
			{
				buffer[s] = 0;
				std::cout<<"Server echo# "<<buffer<<std::endl;
			}
		}
	}
	close(sock);
	return 0;
}
